<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="success" icon="el-icon-plus" style="margin-right: 20px"
        @click="handleCreate">
        新增
      </el-button>
      航线名称：<el-input v-model="listQuery.routeName" placeholder="航线名称" style="width: 200px; margin-right: 20px"
        class="filter-item" @keyup.enter.native="handleFilter" />
      航线类型：<el-select v-model="listQuery.routeType" placeholder="航线类型" clearable
        style="width: 200px; margin-right: 20px" class="filter-item">
        <el-option label="定点航线" value="1" />
        <el-option label="环形航线" value="2" />
        <el-option label="路径跟随航线" value="3" />
      </el-select>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="info" icon="el-icon-refresh-right"
        @click="handleRefresh">
        重置
      </el-button>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column label="序号" prop="id" width="100">
        <template slot-scope="{ row, $index }">
          {{ (listQuery.pageNo - 1) * listQuery.pageSize + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="航线编号" prop="routeNo" />
      <el-table-column label="航线名称" prop="routeName" />
      <el-table-column label="航线类型" prop="routeType">
        <template slot-scope="{ row }">
          <div v-if="row.routeType == 1">定点航线</div>
          <div v-if="row.routeType == 2">环形航线</div>
          <div v-if="row.routeType == 3">路径跟随航线</div>
        </template>
      </el-table-column>
      <el-table-column label="预计飞行里程（km）" width="180px" prop="estimatedFlightMileage" />
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.status == 1" type="success" size="small">启用</el-tag>
          <el-tag v-else type="info" size="small">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <el-button v-if="row.status == 0" size="mini" type="success" @click="handleStatus(row)">
            启用
          </el-button>
          <el-button v-if="row.status == 1" size="mini" type="danger" @click="handleStatus(row)">
            停用
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="700px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
        style="width: 600px; margin-left: 10px">
        <el-form-item label="航线编号" prop="routeNo">
          <el-input v-model="temp.routeNo" placeholder="请输入航线编号" />
        </el-form-item>
        <el-form-item label="航线名称" prop="routeName">
          <el-input v-model="temp.routeName" placeholder="请输入航线名称" />
        </el-form-item>
        <el-form-item label="航线类型" prop="routeType">
          <el-radio-group v-model="temp.routeType" @change="typeChange">
            <el-radio :label="1">定点航线</el-radio>
            <el-radio :label="2">环形航线</el-radio>
            <el-radio :label="3">路径跟随航线</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="temp.routeType == 2" label="环形中心点定位" prop="ringCenterPointPositioning">
          <el-input v-model="temp.ringCenterPointPositioning" placeholder="请选择环形中心点定位" />
        </el-form-item>
        <el-form-item v-if="temp.routeType == 2" label="" prop="">
          <div id="qyContainer" element-loading-text="数据更新中" element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(25,81,135,0.7)" />
        </el-form-item>
        <el-form-item v-if="temp.routeType == 1" label="选择航点" size="small" prop="wayPointNo">
          <!-- <el-button type="primary" icon="el-icon-plus">添加</el-button>
           -->
          <el-select v-model="waypointSel.point" filterable placeholder="请选择" multiple
            style="margin-bottom: 15px; width: 480px" @change="changePoint">
            <el-option v-for="item in wayPointlist" :key="item.id" :label="item.wayPointName" :value="item.wayPointNo">
              <span style="float: left">{{ item.wayPointName }}</span>
              <span style="
                  float: right;
                  color: #8492a6;
                  font-size: 13px;
                  margin-right: 40px;
                ">{{ item.wayPointNo }}</span>
            </el-option>
          </el-select>
          <el-table v-if="waypointData.point.length > 0" :data="waypointData.point" border fit highlight-current-row
            style="width: 100%" size="mini">
            <el-table-column label="序号" prop="id">
              <template slot-scope="{ row, $index }">
                {{ $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="航点编号" prop="wayPointNo" />
            <el-table-column label="航点名称" prop="wayPointName" />
            <el-table-column label="调整顺序">
              <template slot-scope="{ row, $index }">
                <div style="text-align: center">
                  <i v-if="$index != 0" class="el-icon-top" style="font-size: 16px; padding: 0 5px; cursor: pointer"
                    @click="
                      waypointData.point = moveData(
                        waypointData.point,
                        $index,
                        'top'
                      )
                      " />
                  <i v-if="$index != waypointData.point.length - 1" class="el-icon-bottom"
                    style="font-size: 16px; padding: 0 5px; cursor: pointer" @click="
                      waypointData.point = moveData(
                        waypointData.point,
                        $index,
                        'bottom'
                      )
                      " />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="{ row, $index }">
                <el-button size="mini" type="danger" @click="wayPointDelete($index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item v-if="temp.routeType == 2" label="环形半径" prop="ringRadius">
          <el-input v-model="temp.ringRadius" type="number" placeholder="请输入环形半径">
            <template slot="append">米</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="temp.routeType == 2" label="飞行高度" prop="flightHeight">
          <el-input v-model="temp.flightHeight" type="number" placeholder="请输入飞行高度">
            <template slot="append">米</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="temp.routeType == 3" label="选择起点" prop="wayPointStart">
          <!-- <el-button type="primary" icon="el-icon-plus">选择</el-button> -->
          <el-select v-model="waypointSel.start" filterable placeholder="请选择" style="margin-bottom: 15px"
            @change="changeStart">
            <el-option v-for="item in wayPointlist" :key="item.id" :label="item.wayPointName" :value="item.wayPointNo">
              <span style="float: left">{{ item.wayPointName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.wayPointNo
              }}</span>
            </el-option>
          </el-select>
          <el-table v-if="waypointData.start.length > 0" :data="waypointData.start" border fit highlight-current-row
            style="width: 100%" size="mini">
            <el-table-column label="航点编号" prop="wayPointNo" />
            <el-table-column label="航点名称" prop="wayPointName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="{ row, $index }">
                <el-button size="mini" type="danger" @click="
                  waypointSel.start = [];
                waypointData.start = [];
                ">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item v-if="temp.routeType == 3" label="选择终点" prop="wayPointEnd">
          <!-- <el-button type="primary" icon="el-icon-plus">选择</el-button> -->
          <el-select v-model="waypointSel.end" filterable placeholder="请选择" style="margin-bottom: 15px"
            @change="changeEnd">
            <el-option v-for="item in wayPointlist" :key="item.id" :label="item.wayPointName" :value="item.wayPointNo">
              <span style="float: left">{{ item.wayPointName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.wayPointNo
              }}</span>
            </el-option>
          </el-select>
          <el-table v-if="waypointData.end.length > 0" :data="waypointData.end" border fit highlight-current-row
            style="width: 100%" size="mini">
            <el-table-column label="航点编号" prop="wayPointNo" />
            <el-table-column label="航点名称" prop="wayPointName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="{ row, $index }">
                <el-button size="mini" type="danger" @click="
                  waypointSel.end = [];
                waypointData.end = [];
                ">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="飞行速度" type="number" prop="flightSpeed">
          <el-input v-model="temp.flightSpeed" type="number" placeholder="请输入飞行速度">
            <template slot="append">米 / 秒</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="temp.routeType == 2" label="循环间隔时间" prop="cycleIntervalTime">
          <el-input v-model="temp.cycleIntervalTime" type="number" placeholder="请输入循环间隔时间">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="temp.routeType == 3" label="跟随间隔时间" prop="followIntervalTime">
          <el-input v-model="temp.followIntervalTime" type="number" placeholder="请输入跟随间隔时间">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="航线描述" prop="routeDesc">
          <el-input v-model="temp.routeDesc" placeholder="请输入航线描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" :loading="btnLoading"
          @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  waypointList,
  airrouteList,
  airrouteAdd,
  airrouteDel,
  airrouteDetail,
  airrouteUpdate,
  airrouteStatus
} from '@/api/uavairline'
import { formatDate } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
  name: 'Airoute',
  components: { Pagination },
  data() {
    var selStart = (rule, value, callback) => {
      if (!this.waypointSel.start.length) {
        callback(new Error('请选择起点'))
      } else {
        callback()
      }
    }
    var selEnd = (rule, value, callback) => {
      if (!this.waypointSel.end.length) {
        callback(new Error('请选择终点'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      btnLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        routeName: undefined,
        routeType: undefined
      },
      wayPointlist: [],
      waypointSel: {
        point: [],
        start: [],
        end: []
      },
      waypointData: {
        point: [],
        start: [],
        end: []
      },
      temp: {
        id: undefined,
        routeNo: '',
        routeName: '',
        routeType: 1,
        routeDesc: '',
        flightSpeed: '',

        wayPointNo: [],

        ringCenterPointPositioning: '',
        ringRadius: '',
        flightHeight: '',
        cycleIntervalTime: '',

        followIntervalTime: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        routeNo: [
          { required: true, message: '请输入航线编号', trigger: 'blur' }
        ],
        routeName: [
          { required: true, message: '请输入航线名称', trigger: 'blur' }
        ],
        routeType: [
          { required: true, message: '请选择航线类型', trigger: 'change' }
        ],
        wayPointNo: [
          { required: true, message: '请选择航点', trigger: 'change' }
        ],
        flightSpeed: [
          { required: true, message: '请输入飞行速度', trigger: 'blur' }
        ],
        routeDesc: [
          { required: true, message: '请输入航线描述', trigger: 'blur' }
        ],
        ringCenterPointPositioning: [
          {
            required: true,
            message: '请选择环形中心点定位',
            trigger: 'change'
          }
        ],
        ringRadius: [
          { required: true, message: '请输入环形半径', trigger: 'blur' }
        ],
        flightHeight: [
          { required: true, message: '请输入飞行高度', trigger: 'blur' }
        ],
        cycleIntervalTime: [
          { required: true, message: '请输入循环间隔时间', trigger: 'blur' }
        ],
        wayPointStart: [
          {
            required: true,
            validator: selStart,
            trigger: 'change'
          }
        ],
        wayPointEnd: [
          {
            required: true,
            validator: selEnd,
            trigger: 'change'
          }
        ],
        followIntervalTime: [
          { required: true, message: '请输入跟随间隔时间', trigger: 'blur' }
        ]
      },
      center: [126.578085, 43.859222],
      AMap: null,
      markers: [
        {
          name: '',
          lat: '',
          lng: ''
        }
      ],
      marker:[]
    }
  },
  created() {
    this.getList()
    this.getWappoint()
  },
  mounted() {
    window._AMapSecurityConfig = {
      securityJsCode: 'e5c0fe8d40233deb748b07cfa09ab739'
    }
  },
  methods: {
    init(row = null) {
      this.$nextTick(() => {
        AMapLoader.load({
          key: '3bccb9b5337ca1ae0bd58577c6f1ed14',
          version: '2.0',
          plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.LngLat', 'AMap.Marker'],
          AMapUI: {
            version: '1.1',
            plugins: ['overlay/SimpleMarker']
          }
        })
          .then((AMap) => {
            this.AMap = AMap
            this.map = new AMap.Map('qyContainer', {
              viewMode: '2D',
              zoom: 14,
              // mapStyle: 'amap://styles/darkblue', // 地图样式，可以自定义
              center:
                row && row.ringCenterPointPositioning
                  ? [
                    row.ringCenterPointPositioning.split(',')[0],
                    row.ringCenterPointPositioning.split(',')[1]
                  ]
                  : this.center
            })

            // 添加toolbar--放大缩小
            const toolbar = new AMap.ToolBar()
            this.map.addControl(toolbar)
            this.map.on('click', this.clickMapHandler)
            if (row && row.ringCenterPointPositioning) {
              this.map && this.map.remove(this.markers)
              this.markers = [
                {
                  // name: row.routeName,
                  lat: row.ringCenterPointPositioning.split(',')[1],
                  lng: row.ringCenterPointPositioning.split(',')[0]
                }
              ]
              this.addMarkers()
            }
          })
          .catch((e) => {
            console.log(e)
          })
      })
    },
    addMarkers() {
      const AMap = this.AMap
      if (AMap) {
        this.markers.forEach((item, index) => {
          if (item.lat && item.lng) {
            const obj = {
              position: new AMap.LngLat(item.lng, item.lat),
              zIndex: 99
            }
            this.marker = new AMap.Marker(obj)
            this.map.add([this.marker])
            // this.markers.push(marker2, marker);
          }
        })
      }
    },
    clickMapHandler(e) {
      this.temp.ringCenterPointPositioning =
        e.lnglat.getLng() + ',' + e.lnglat.getLat()
      this.map && this.marker && this.map.remove(this.marker)
      this.markers = [
        {
          name: '',
          lat: e.lnglat.getLat(),
          lng: e.lnglat.getLng(),
        }
      ]
      this.addMarkers()
      this.map.setCenter([e.lnglat.getLng(), e.lnglat.getLat()]);
    },
    typeChange(e) {
      if (e == 2) {
        this.init()
      }
      this.resetFrom()
    },
    changePoint(e) {
      this.waypointData.point = []
      e.forEach((val, index) => {
        const info = this.wayPointlist.filter((v) => {
          return v.wayPointNo == val
        })
        this.waypointData.point.push(info[0])
      })
      this.temp.wayPointNo = e.length ? e.join(',') : ''
    },
    wayPointDelete(index) {
      this.waypointData.point.splice(index, 1)
      this.waypointSel.point.splice(index, 1)
      const arr = this.temp.wayPointNo.split(',')
      arr.splice(index, 1)
      this.temp.wayPointNo = arr.join(',')
    },
    changeStart(e) {
      const info = this.wayPointlist.filter((v) => {
        return v.wayPointNo == e
      })
      this.waypointData.start = info
    },
    changeEnd(e) {
      const info = this.wayPointlist.filter((v) => {
        return v.wayPointNo == e
      })
      this.waypointData.end = info
    },
    getWappoint() {
      waypointList({
        pageNo: 1,
        pageSize: 200
      }).then((response) => {
        this.wayPointlist = response.list
      })
    },

    getList() {
      this.listLoading = true
      airrouteList(this.listQuery).then((response) => {
        this.list = response.list
        this.total = response.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleRefresh() {
      (this.listQuery = {
        pageNo: 1,
        pageSize: 20,
        routeName: undefined,
        routeType: undefined
      }),
        this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        routeNo: '',
        routeName: '',
        routeType: 1,
        routeDesc: '',
        flightSpeed: '',

        wayPointNo: [],

        ringCenterPointPositioning: '',
        ringRadius: '',
        flightHeight: '',
        cycleIntervalTime: '',

        followIntervalTime: ''
      }
    },
    resetFrom() {
      this.temp.flightSpeed = ''
      this.temp.wayPointNo = []
      this.temp.ringCenterPointPositioning = ''
      this.temp.ringRadius = ''
      this.temp.flightHeight = ''
      this.temp.cycleIntervalTime = ''
      this.temp.followIntervalTime = ''
      this.waypointSel = {
        point: [],
        start: [],
        end: []
      }
      this.waypointData = {
        point: [],
        start: [],
        end: []
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate() {
      this.resetTemp()
      this.resetFrom()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.routeType == 2) {
            this.temp.wayPointNo = ''
          }
          if (this.temp.routeType == 3) {
            this.temp.wayPointNo =
              this.waypointData.start[0].wayPointNo +
              ',' +
              this.waypointData.end[0].wayPointNo
          }
          this.btnLoading = true
          airrouteAdd(this.temp).then(() => {
            this.btnLoading = false
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch((error) => {
            this.btnLoading = false
          })
        }
      })
    },
    handleUpdate(row) {
      airrouteDetail({ id: row.id }).then((res) => {
        this.temp.id = res.id
        this.temp.routeNo = res.routeNo
        this.temp.routeName = res.routeName
        this.temp.routeType = res.routeType
        this.temp.routeDesc = res.routeDesc
        this.temp.flightSpeed = res.flightSpeed
        this.temp.wayPointNo = res.wayPointNo ? res.wayPointNo.split(',') : []
        if (res.routeType == 1) {
          this.waypointSel.point = res.wayPointNo.split(',')
          var arr = []
          this.temp.wayPointNo.forEach((val, index) => {
            const info = this.wayPointlist.filter((v) => {
              return v.wayPointNo == val
            })
            arr.push(info[0])
          })
          this.waypointData.point = arr
        }
        if (res.routeType == 2) {
          this.temp.ringCenterPointPositioning = res.ringCenterPointPositioning
          this.temp.ringRadius = res.ringRadius
          this.temp.flightHeight = res.flightHeight
          this.temp.cycleIntervalTime = res.cycleIntervalTime
          this.init(res)
        }
        if (res.routeType == 3) {
          this.waypointSel.start = this.temp.wayPointNo[0]
          this.waypointSel.end = this.temp.wayPointNo[1]
          this.waypointData.start = this.wayPointlist.filter((v) => {
            return v.wayPointNo == this.temp.wayPointNo[0]
          })
          this.waypointData.end = this.wayPointlist.filter((v) => {
            return v.wayPointNo == this.temp.wayPointNo[1]
          })
          this.temp.followIntervalTime = res.followIntervalTime
        }
        this.temp.wayPointNo = this.temp.wayPointNo
          ? this.temp.wayPointNo.join(',')
          : ''
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.routeType == 3) {
            this.temp.wayPointNo =
              this.waypointData.start[0].wayPointNo +
              ',' +
              this.waypointData.end[0].wayPointNo
          }
          const tempData = Object.assign({}, this.temp)
          this.btnLoading = true
          airrouteUpdate(tempData).then(() => {
            this.btnLoading = false
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch((error) => {
            this.btnLoading = false
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该航线？')
        .then(() => {
          airrouteDel(row.id).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        })
        .catch(() => { })
    },
    handleStatus(row) {
      this.$confirm(`确定${row.status == 1 ? '停用' : '启用'}该航线？`)
        .then(() => {
          airrouteStatus({
            status: row.status == 1 ? 0 : 1,
            id: row.id
          }).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        })
        .catch(() => { })
    },
    moveData(arr, index, type) {
      const _firstIndex = type === 'top' ? index - 1 : index
      const _lastIndex = type === 'top' ? index : index + 1
      // 处理后的数据
      const _handleData = this.swapArray(arr, _firstIndex, _lastIndex)
      const ids = []
      _handleData.forEach((item, index) => {
        ids.push(item.wayPointNo)
      })
      this.temp.wayPointNo = ids.join(',')
      return _handleData
    },
    swapArray(arr, firstIndex, lastIndex) {
      if (firstIndex === -1 || lastIndex === arr.length) {
        this.$message.warning(
          `${firstIndex === -1 ? '已经处在第一的位置了' : '已经处在末尾的位置了'
          }`
        )
        return arr
      }
      arr[firstIndex] = arr.splice(lastIndex, 1, arr[firstIndex])[0]
      return arr
    }
  }
}
</script>
<style lang="scss" scoped>
#qyContainer {
  padding: 0px;
  margin: 0px;
  width: 500px;
  height: 300px;
}
</style>
